<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card视图 -->
    <el-card class="box-card">
        <!-- 用户搜索框 -->
      <el-input  style="width:30%" placeholder="请输入内容" v-model="queryUser.query" clearable @clear="clearInput()"><el-button slot="append" icon="el-icon-search" @click="searchUser()"></el-button></el-input>
      <el-button type="primary" @click="addUser()">添加用户</el-button>
      <!-- 表格 -->
    <el-table
        :data="usersList"
        border
        style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="changeUserStatus(scope.row.id,scope.row.mg_state)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                <!-- 编辑 -->
                <el-tooltip effect="dark" content="编辑用户" placement="top-start" :enterable="false">
                    <el-button type="primary" size="mini" @click="editUserInfo(scope.row)"><i class="el-icon-edit"></i></el-button>
                </el-tooltip>
                 <!-- 删除 -->
                 <el-tooltip effect="dark" content="删除用户" placement="top-start" :enterable="false">
                    <el-button type="danger" size="mini" @click="deleteUser(scope.row)"><i class="el-icon-delete"></i></el-button>
                </el-tooltip>
                 <!-- 分配角色 -->
                 <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
                    <el-button type="warning" size="mini" @click="setRoles(scope.row)"><i class="el-icon-setting"></i></el-button>
                 </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
       @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryUser.pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="queryUser.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 编辑用户对话框 -->
    <el-dialog
        title="修改用户信息"
        :visible.sync="dialogVisible"
        width="50%"
        @close="closeDialog()"
        >
       <!-- 修改 -->
       <el-form ref="userEdit" :model="userInfo" :rules="rules" label-width="80px">
            <el-form-item label="用户名">
                <el-input v-model="userInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="userInfo.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
       </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitUserEdit()">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 添加用户对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="adddialogVisible"
        width="50%"
        @close="closeAddDiolog()"
        >
        <!-- 添加信息 -->
        <el-form ref="addUserForm" :model="addUserForm" :rules="addUserRules" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="adddialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddUser()">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
        title="提示"
        :visible.sync="setRolesDialog"
        width="50%"
        @close="settingRoleClose"
        >
        <div>
            <p>当前的用户：{{this.roleInfo.username}}</p>
            <p>当前的角色：{{this.roleInfo.role_name}}</p>
             <p>分配新角色：
                 <el-select v-model="seletedId" placeholder="请选择">
                    <el-option
                    v-for="item in rolesList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
                    </el-option>
                </el-select>
             </p>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRolesDialog = false">取 消</el-button>
            <el-button type="primary" @click="clickSettingRole()">确 定</el-button>
        </span>
        </el-dialog>
  </div>
</template>
<script>
export default {
    data(){
        var checkEmail=(rule,value,callback)=>{
            var reg=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
            if(reg.test(value)) return callback();
            callback(new Error('请输入正确的邮箱'));
        };
        var checkMobile=(rule,value,callback)=>{
            var reg=/^1(3|4|5|6|7|8|9)\d{9}$/
            if(reg.test(value)) return callback();
            callback(new Error('请输入正确的手机号'));
        };
        return{
            input3:'',
            queryUser:{
                query:'',
                pagenum:1,
                pagesize:4
            },
            usersList:[],
            rolesList:[],
            seletedId:'',
            total:0,
            //修改用户
            dialogVisible:false,
            //添加用户
            adddialogVisible:false,
            setRolesDialog:false,
            roleInfo:{},
            userInfo:{},
            addUserForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addUserRules:{
                username:[
                     { required: true, message: '请输入用户名', trigger: 'blur' },
                     { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                ],
                password:[
                     { required: true, message: '请输入密码', trigger: 'blur' },
                     { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                mobile:[
                     { required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: checkMobile, trigger: 'blur' }
                ],
                email:[
                     { required: true, message: '请输入邮箱', trigger: 'blur' },
                     { validator: checkEmail, trigger: 'blur' }
                ]
            },
            rules:{
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            }
            
        }
    },
    created(){
        this.gerUserList();
    },
    methods:{
        //提交addUser表单
        submitAddUser(){
            this.$refs.addUserForm.validate(async valid=>{
                if(!valid) return this.$message.warning('表单验证不通过')
                var {data:res}=await this.$http.post('users',this.addUserForm);
                if(res.meta.status!==201) return this.$message.error('添加失败')
                this.$message.success('添加成功');
                this.gerUserList();
                this.adddialogVisible=false
            })
            
           
        },
        //关闭addUserdiolog
        closeAddDiolog(){
            this.$refs.addUserForm.resetFields();
        },
        //添加用户
        addUser(){
            this.adddialogVisible=true
        },
        //清空刷新请求
        clearInput(){
            this.queryUser.query='';
            this.gerUserList();
        },
        //查询用户
        searchUser(){
            this.gerUserList();
        },
        //删除用户  
        async deleteUser(user){
           var res1=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err=>err)
            console.log(res1)
            if(res1=='confirm'){
                const {data:res}=await this.$http.delete('users/'+user.id)
                if(res.meta.status!==200) return this.$message.error('删除失败')
                this.$message.success('删除成功')
                this.gerUserList();
            }else{
                this.$message.info('已取消删除')
            }
            
        },
        //编辑用户
        editUserInfo(val){
            this.userInfo=val;
            this.dialogVisible=true;
        },
        //获取用户数据
        async gerUserList(){
            const {data:res}=await this.$http.get('users',{params:this.queryUser})
            
            if(res.meta.status!==200) return this.$message.error('获取用户数据失败')
            this.usersList=res.data.users;
            this.total=res.data.total;
            console.log(this.usersList)
        },
        //页面条数改变
        handleSizeChange(val){
            this.queryUser.pagesize=val;
            this.gerUserList();
        },
        handleCurrentChange(val){
            this.queryUser.pagenum=val;
            this.gerUserList();
        },
        //改变用户状态
        async changeUserStatus(id,type){
            const {data:res}=await this.$http.put(`users/${id}/state/${type}`,{
                uId:id,
                type:type
            })
            if(res.meta.status!==200) return this.$message.error('改变状态失败');
        },
        //关闭对话框
        closeDialog(){
            this.$refs.userInfo.resetFields();
            this.gerUserList();
        },
        //提交用户修改
        submitUserEdit(){
             this.$refs.userEdit.validate(async valid => {
                if(!valid) return this.$message.error('修改失败')
                const {data:res}=await this.$http.put('users/'+this.userInfo.id,{
                    email:this.userInfo.email,
                    mobile:this.userInfo.mobile,
                })
                if(res.meta.status!==200) return this.$message.error('更新失败')
                this.$message.success('更新成功')
                this.dialogVisible=false;   
                this.gerUserList();
            });
        },
        //分配角色
        async setRoles(role){
            this.roleInfo=role;
            //获取角色列表
            var {data:res}=await this.$http.get('roles')
            if(res.meta.status!==200) return this.$message.error('获取角色列表失败')
            this.rolesList=res.data;
            this.setRolesDialog=true;
        },
        //点击分配角色对话框
       async clickSettingRole(){
            if(!this.seletedId){
                return this.$message.info('请选择分配角色')
            }
            var {data:res}=await this.$http.put(`users/${this.roleInfo.id}`,{rid:this.seletedId})
            console.log(res)
            if(res.meta.status!==200) return this.$message.error('修改角色失败')
            this.$message.success('分配角色成功')
            console.log(res)
            this.gerUserList();
            this.setRolesDialog=false;
        },
        //监听分配角色对话框关闭
        settingRoleClose(){
            this.roleInfo={},
            this.rolesList=[],
            this.seletedId=''
        }
        
    }
};
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.el-input{
    margin-right: 25px;
}
.el-table{
    margin-top: 20px;
}
</style>